const Task = require('../models/task')
const Journal = require('../models/journal')
const User = require('../models/user')
const Category = require('../models/category')
const Notic = require('../models/notice')

const fs = require('fs')
let path = require('path')
const response = require('../utils/response')

// 上传
exports.updata = async (req, res, next) => {
    try {
        const files = req.files
        if (files.length == 0) {
            return response(res, 401, '没有选择文件', files)
        }
        for (var i in files) {
            let oldname = req.files[i].path //获取path
            let newname = req.files[i].path + '-' + req.files[i].originalname
            fs.renameSync(oldname, newname)
        }
        // res.send("https://quanquan.asia/" + files[0].destination + files[0].originalname)
        // console.log(files);
        // res.send(files)
        // return
        response(res, 200, '上传成功', files)
    } catch (err) {
        next(err)
    }
}


// 下载
exports.download = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        const filename = req.query.filename
        var task = await Task.findById(taskId)
        if (!task) {
            return response(res, 404, '找不到该任务', task)
        }
        for (var i in task.fileAddress) {
            var tasksplit = task.fileAddress[i].split('/')
            var taskfile = tasksplit.pop()
            if (filename == taskfile) {
                res.download(task.fileAddress[i])
            }
        }
    } catch (err) {
        next(err)
    }
}